//
//  DeviceConfig.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/22.
//


import Foundation
import UIKit

// MARK: - 全局常量
enum AppConstants {
    static let tabBarHeight: CGFloat = 62.0
    static let screenWidth: CGFloat = UIScreen.main.bounds.width
    static let screenHeight: CGFloat = UIScreen.main.bounds.height
    
    enum Language {
        static let english = "en"
        static let indonesian = "id"
    }
}

// MARK: - 本地化工具
final class LocalizationManager {
    static let shared = LocalizationManager()
    
    private var currentLanguage: String = AppConstants.Language.english
    private var fallbackLanguage: String = AppConstants.Language.english
    
    private init() {
        setupCurrentLanguage()
    }
    
    private func setupCurrentLanguage() {
        // 根据业务逻辑设置当前语言
        if WJAppEnvironment.shared.currentCountry == .indonesia {
            currentLanguage = AppConstants.Language.indonesian
        }
    }
    
    func localizedString(_ key: String, comment: String = "") -> String {
        // 1. 尝试当前语言
        if let localizedString = localizedString(for: key, in: currentLanguage) {
            return localizedString
        }
        
        // 2. 回退到英文
        if let englishString = localizedString(for: key, in: fallbackLanguage) {
            return englishString
        }
        
        // 3. 返回原始key
        return key
    }
    
    private func localizedString(for key: String, in language: String) -> String? {
        guard let bundlePath = Bundle.main.path(forResource: language, ofType: "lproj"),
              let languageBundle = Bundle(path: bundlePath) else {
            return nil
        }
        
        let localizedString = languageBundle.localizedString(forKey: key, value: nil, table: nil)
        return localizedString != key ? localizedString : nil
    }
}

// 便捷访问方法
func localizedString(_ key: String, comment: String = "") -> String {
    return LocalizationManager.shared.localizedString(key, comment: comment)
}

// MARK: - 随机字符串生成
enum RandomStringGenerator {
    private static let allowedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    
    static func generate(length: Int = 8) -> String {
        let validLength = max(6, min(length, 20)) // 限制长度范围 6-20
        let characters = (0..<validLength).map { _ in
            allowedCharacters.randomElement() ?? "a"
        }
        return String(characters)
    }
}

// MARK: - 设备标识符
enum DeviceIdentifier {
    static var vendorIdentifier: String {
        if let idfv = NDKeychainTool.shared.readString(forKey: NDIdfvKey) {
            return idfv
        }
        
        return UIDevice.current.identifierForVendor?.uuidString ?? ""
    }
}
